using CoreCms.Net.Identity.Authorization.Extensions;
using CoreCms.Net.Identity.Authorization.Requirements;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;

namespace CoreCms.Net.Identity.Authorization.Handlers
{
    /// <summary>
    /// 权限授权处理器
    /// </summary>
    public abstract class SilkyAuthorizationPermissionHandlerBase : AuthorizationHandler<PermissionRequirement>
    {
        // 重写异步处理程序
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement)
        {
            if (context.User == null)
            {
                return Task.CompletedTask;
            }
            var found = false;
            var isAuthenticated = context.User.Identity?.IsAuthenticated;
            if (isAuthenticated == true)
            {
                found = PolicyPipelineAsync(context, context.GetCurrentHttpContext(), requirement).Result;
            }

            if (found)
            {
                context.Succeed(requirement);
            }
            else
            {
                context.Fail();
            }

            return Task.CompletedTask;
        }

        /// <summary>
        /// 策略验证管道
        /// </summary>
        /// <param name="context"></param>
        /// <param name="httpContext"></param>
        /// <param name="requirement"></param>
        /// <returns></returns>
        protected virtual Task<bool> PolicyPipelineAsync(AuthorizationHandlerContext context, HttpContext httpContext
            , PermissionRequirement requirement)
        {
            return Task.FromResult(true);
        }
    }
}